import { createSlice } from "@reduxjs/toolkit";
import axios from 'axios'

const channelStore = createSlice({
    name: 'channelStore',
    initialState: {
        channelList: []
    },
    reducers: {
        setChannels(state, action){
            state.channelList = action.payload
        },
    }
})

const { setChannels } = channelStore.actions
const reducer = channelStore.reducer

// 异步方法中要用到 dispatch，同时在这之前要解构出 actions 中的方法名称
const fetchChannelList = dispatch => {
    const URL = 'http://geek.itheima.net/v1_0/channels';
    // return () => {
    //     axios.get(URL).then(res =>{
    //         console.log(res.data.data.channels)
    //         dispatch(setChannels(res.data.data.channels))
    //     }).catch(e => console.log('请求channelList时出现异常：',e))
    // }
    return async () => {
        const res = await axios.get(URL)
        dispatch(setChannels(res.data.data.channels))
    }
}

export { setChannels, fetchChannelList }
export default reducer
